<?php if (!defined('ROOT_DIR')) exit('No direct script access!');
/**
 *@author Ervin R. Musngi <ervimusngi@gmail.com>
 *@copyright Copyright (c) 2012, Ervin Musngi
 *@DateCreated - December 2, 2011
 *@DateModified - December 2, 2011
 *
 *  #Database Class - Library for MySql Driver
 *   This contains all basic Query Building Methods
 *
 */
class Database {
    
    private     $_host;
    private     $_db_name;
    private     $_username;
    private     $_password;
    private     $_connection;
    private     $_prefix;
    
    private     $_select = array();
    private     $_where  = array();
    private     $_table;
    private     $_result;
    
    public      $id;
    
    
    public function __construct() {
        
        $db         = get_config('database','db');
        $active     = get_config('database','active_group'); 
        
        $this->_host            = $db[$active]['host'];
        $this->_username        = $db[$active]['username'];
        $this->_password        = $db[$active]['password'];
        $this->_db_name         = $db[$active]['database'];
        $this->_prefix          = $db[$active]['prefix'];
        $this->_connection      = null;
    }
    
    public function __destruct()
    {
        $this->_host        = null;
        $this->_db_name     = null;
        $this->_password    = null;
        $this->_username    = null;
        $this->_connection  = null;
    }
   
    private function _establishConnection()
    {
        if($this->_connection) { return $this->_connection; }
        try {
            
            $this->_connection = mysql_connect($this->_host,$this->_username,$this->_password);
            
            mysql_select_db($this->_db_name);
            
            
            return $this->_connection;
            
        } catch(Exception $e) {
            throw $e;
        }
    }
    
    
    /*
     *@param string $sql - placeholder for sql statement
     */
    public function query( $sql = "" )
    {
        try {
            $this->_result =  mysql_query($sql,$this->_establishConnection());
            return $this;
        } catch (Exception $e) {
            throw $e;
        }
    }
    
    public function result()
    {
        $data = array();
        
        while($row = mysql_fetch_object($this->_result))
        {
            $data[] = $row;
        }
        
        return (object)$data;
    }
    
    public function row()
    {
        return  mysql_fetch_object($this->_result);
    }
    
    public function select($column = '',$escape = TRUE)
    {
        
        if (is_array($column))
        {
            foreach ($column as $c)   
            {
                if ($escape === TRUE)
                {
                    $this->_select[] = '`'.$c.'`';
                }
                else
                {
                    $this->_select[] = $c;
                }
            }
            
        }
        elseif ($column!='')
        {
            if ($escape === TRUE)
            {
                $this->_select[] = '`'.$column.'`';
            }
            else
            {
                $this->_select[] = $column;
            }
        }
        
        return $this;
    
    }
    
    public function from($table = '')
    {
        if ( $table != '' )
        {
            $this->_table = $this->_prefix.$table;
            
            return $this;
        }
        else
        {
            exit('No table specified!');
        }
    }
    
    public function where($column,$value=NULL, $type = "AND ")
    {

        if (!is_array($column))
        {
            $column = array($column=>$value);
        }
        
        $prefix = (count($this->_where) == 0) ? '' : $type;    
        
        foreach ($column as $k => $v)
        {
            if (is_null($v) && ! $this->_has_operator($k))
            {
                $k = "`{$k}` IS NULL ";
            }
            
            if ( ! is_null($v))
            {
                $v = "'".$v."'";
                
                if ( ! $this->_has_operator($k))
                {
                    $k = "`{$k}` = ";
                }
            
            }
            
            $this->_where[] = $prefix.$k.$v;
        }
        
        return $this;
    }
    
    public function or_where($column,$value='')
    {
        return $this->_where($column, $value, 'OR ');
    }
    
    public function get($limit='',$offset=0)
    {
        
        if (count($this->_select) > 0)
        {
            $select = implode(",",$this->_select);
        }
        else
        {
            $select = " * ";
        }
        
        if ($this->_table != '')
        {
            $table = $this->_table;
        }
        
        if ( count($this->_where) > 0 )
        {
            $where = " WHERE ".implode(" ",$this->_where);
        }
        else
        {
            $where = "";
        }
        
        $sql = " SELECT ".$select." FROM `".$table."` ".$where;
        $this->clear();
        return $this->query($sql);
        
    }
    
    private function _has_operator($str)
	{
		$str = trim($str);
		if ( ! preg_match("/(\s|<|>|!|=|is null|is not null)/i", $str))
		{
			return FALSE;
		}

		return TRUE;
	}
    
    public function insert($table,$data)
    {
        try {
            
            $fields = array();
            $value = array();
            foreach($data as $k=>$v) {
                
                $fields[] = "`".$k."`";
                $value[]  = "'".mysql_escape_string($v)."'";
            
            }
            
            $f = implode(',',$fields);
            $val = implode(',',$value);
            
            $table = $this->_prefix.$table;
            
            $sql = "INSERT INTO `{$table}`({$f}) VALUES({$val})";
            
            $this->query($sql);
            
            $this->id =  mysql_insert_id();
            
            $this->clear();
            
            return $this;
            
        } catch (Exception $e) {
            throw $e;
        }
    }
    
    public function update($data)
    {
        
        if ($this->_table == '')
        {
            return;
        }
        
        if ( count($this->_where) > 0 )
        {
            $where = " WHERE ".implode(" ",$this->_where);
        }
        else
        {
            $where = "";
        }

        $fields = array();
        $value = array();
        foreach($data as $k=>$v) {
            $fields[] = " `{$k}` = '".mysql_escape_string($v)."' ";
        }
        
        $f = implode(',',$fields);
           
        $sql = "UPDATE ".$this->_table." SET {$f} ".$where;
        
        
        $this->query($sql);
        
        $this->clear();
        
    }
    
    public function clear()
    {
        $this->_where = null;
        $this->_select = null;
        $this->_table = null;
    }
    
    public function delete()
    {
        if ($this->_table == '')
        {
            return;
        }
        
        if ( count($this->_where) > 0 )
        {
            $where = " WHERE ".implode(" ",$this->_where);
        }
        else
        {
            $where = "";
        }
        
        
        $sql = "DELETE FROM ".$this->_table.$where;
        
        $this->query($sql);
        
        $this->clear();
        
    }
}